package ch.bfh.abcm.rems.sensors.tinkerforge;

import java.util.ArrayList;

import org.apache.log4j.Logger;

import ch.bfh.abcm.rems.interfaces.SensorController;
import ch.bfh.abcm.rems.interfaces.tinkerforge.TFSensor;
import ch.bfh.abcm.rems.interfaces.tinkerforge.TFSensorDataPersister;
import ch.bfh.abcm.rems.sensors.tinkerforge.tfsensors.REMSAmbientLightSensor;
import ch.bfh.abcm.rems.sensors.tinkerforge.tfsensors.REMSHumiditySensor;
import ch.bfh.abcm.rems.sensors.tinkerforge.tfsensors.REMSTempSensor;

import com.tinkerforge.IPConnection;

public class TFSensorController implements SensorController {

    private static Logger logger = Logger.getLogger("play");

    private ArrayList<TFSensor> sensors = new ArrayList<TFSensor>();
    private TFSensorDataPersister persister;

    public TFSensorController(TFConfig config) {
        this.persister = config.getDataPersister();
        sensors = createTFSensors(config.getSensorDefinitions());
    }

    @Override
    public void connectToAvailableSensors() {
        for (TFSensor tfSensor : sensors) {
            tfSensor.connect();
            tfSensor.setCallBackPeriod(tfSensor.getCallBackPeriod());
        }
    }

    @Override
    public void disconnectSensors() {
        for (TFSensor tfSensor : sensors) {
            tfSensor.disconnect();
        }
    }

    private ArrayList<TFSensor> createTFSensors(ArrayList<TFSensorConfigDefinition> sensorDefinitions) {
        ArrayList<TFSensor> rv = new ArrayList<TFSensor>();
        for (TFSensorConfigDefinition sensorDefinition : sensorDefinitions) {
            String uid = sensorDefinition.getUid();
            String host = sensorDefinition.getHost();
            int port = sensorDefinition.getPort();
            long callBackPeriod = sensorDefinition.getCallBackPeriod();
            IPConnection ipcon = new IPConnection();
            switch (sensorDefinition.getSensorType()) {
            case AMBIENT:
                logger.info("Creating new Ambinetsensor: {uid=" + uid + " host=" + host + "}");
                rv.add(new REMSAmbientLightSensor(uid, ipcon, host, port, persister,callBackPeriod));
                break;
            case TEMPERATURE:
                logger.info("Creating new Tempersturesensor: {uid=" + uid + " host=" + host + "}");
                rv.add(new REMSTempSensor(uid, ipcon, host, port, persister,callBackPeriod));
                break;
            case HUMIDITY:
                logger.info("Creating new Humiditysensor: {uid=" + uid + " host=" + host + "}");
                rv.add(new REMSHumiditySensor(uid, ipcon, host, port, persister,callBackPeriod));
                break;
            default:
                logger.error("Sensortype {" + sensorDefinition.getSensorType() + "} is not implementet in this version");
                break;
            }
        }
        return rv;
    }

}
